package com.changgou.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.entity.ResultCode;
import com.changgou.goods.dao.*;
import com.changgou.goods.exception.MyBaseException;
import com.changgou.goods.pojo.*;
import com.changgou.goods.service.SpuService;
import com.changgou.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class SpuServiceImpl implements SpuService {

    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private CategoryBrandMapper categoryBrandMapper;

    /**
     * @param goods
     * @return void
     * @description: 新增商品的spu
     * @author 大佬味的小男孩
     * @date 2020/07/19 16:45
     */
    @Override
    @Transactional
    public void add(Goods goods) {
        //添加spu
        Spu spu = goods.getSpu();
        //添加分布式id
        spu.setId(String.valueOf(idWorker.nextId()));
        spu.setIsDelete("0"); //设置删除状态
        spu.setIsMarketable("0"); //设置上架状态
        spu.setStatus("0");//设置审核状态
        spuMapper.insertSelective(spu);
        //添加sku
        this.saveSkuList(goods);
    }

    /**
     * @param id
     * @return com.changgou.goods.pojo.Goods
     * @description: 根据ID查询 SPU和SKU列表
     * @author 大佬味的小男孩
     * @date 2020/07/19 22:08
     */
    @Override
    public Goods findGoodsById(String id) {
        Goods goods = new Goods();
        //查询spu
        Spu spu = spuMapper.selectByPrimaryKey(id);
        goods.setSpu(spu);
        //查询sku
        Example example = new Example(Sku.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("spuId", id);
        List<Sku> skuList = skuMapper.selectByExample(example);
        goods.setSkuList(skuList);
        return goods;
    }

    /**
     * @param goods
     * @return void
     * @description: 保存修改
     * @author 大佬味的小男孩
     * @date 2020/07/19 22:36
     */
    @Override
    public void update(Goods goods) {
        //取出spu部分
        Spu spu = goods.getSpu();
        spuMapper.updateByPrimaryKeySelective(spu);
        /*
         * spu和sku修改后 原来的 tb_category_brand 中的 关联关系作废
         * */
        //删除原sku列表
        Example example = new Example(Sku.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("spuId", spu.getId());
        skuMapper.deleteByExample(example);
        saveSkuList(goods);//保存sku列表
    }

    /**
     * @param id
     * @return void
     * @description: 审核并自动上架
     * @author 大佬味的小男孩
     * @date 2020/07/19 23:04
     */
    @Override
    @Transactional
    public void audit(String id) {
        //根据id 查询spu 商品
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //判断商品是否存在
        if (spu == null) {
            MyBaseException.throwe(ResultCode.DATA_NOT_EXIST);
        }
        //校验是否是删除商品
        if ("1".equals(spu.getIsDelete())) {
            MyBaseException.throwe(ResultCode.ITEM_DELETED);
        }
        //校验是否已审核
        if ("1".equals(spu.getStatus())) {
            //throw new MyBaseException(ResultCode.ITEM_APPROVED);
            MyBaseException.throwe(ResultCode.ITEM_APPROVED);
        }
        //如果未删除则修改审核状态为1
        spu.setStatus("1");
        //自动上下架
        spu.setIsMarketable("1");
        //修改数据库信息
        spuMapper.updateByPrimaryKeySelective(spu);

    }


    /**
     * @param id
     * @return void
     * @description: 下架商品
     * @author 大佬味的小男孩
     * @date 2020/07/20 16:11
     */
    @Override
    @Transactional
    public void pull(String id) {

        //根据id 查询spu 商品
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //判断商品是否存在
        if (spu == null) {
            MyBaseException.throwe(ResultCode.DATA_NOT_EXIST);
        }
        //判断商品是否删除
        if ("1".equals(spu.getIsDelete())) {
            MyBaseException.throwe(ResultCode.ITEM_DELETED);
        }
        //判断商品是否已经下架
        if ("0".equals(spu.getIsMarketable())) {
            MyBaseException.throwe(ResultCode.GOODS_OFF_THE_SHELF);
        }
        //修改商品的状态为下架状态
        spu.setIsMarketable("0");
        spu.setStatus("0");
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     * @param id
     * @return void
     * @description: 逻辑中删除商品，并非真正的删除(物理删除)，而是采用逻辑删除将删除标记的字段设置为1
     * @author 大佬味的小男孩
     * @date 2020/07/20 18:37
     */
    @Override
    @Transactional
    public void delete(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //判断商品是否存在
        if (spu == null) {
            MyBaseException.throwe(ResultCode.DATA_NOT_EXIST);
        }
        //判断商品是否删除
        if ("1".equals(spu.getIsDelete())) {
            MyBaseException.throwe(ResultCode.ITEM_DELETED);
        }
        //判断商品是否下架
        if ("1".equals(spu.getIsMarketable())) {
            MyBaseException.throwe(ResultCode.GOODS_OF_THE_SHELF);
        }
        //设置商品删除状态
        spu.setIsDelete("1");
        //更新数据库
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     * @param id
     * @return void
     * @description: 回收站中还原商品, 将删除标记的字段设置为0
     * @author 大佬味的小男孩
     * @date 2020/07/20 18:38
     */
    @Override
    @Transactional
    public void reduction(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //判断商品是否存在
        if (spu == null) {
            MyBaseException.throwe(ResultCode.DATA_NOT_EXIST);
        }
        //判断是否删除
        if ("0".equals(spu.getIsDelete())) {
            MyBaseException.throwe(ResultCode.ITEM_NOT_DELETED);
        }
        //判断商品已还原
        if ("0".equals(spu.getIsDelete())) {
            MyBaseException.throwe(ResultCode.ITEM_RESTORED);
        }
        //还原商品
        spu.setIsDelete("0");
        //更新数据库
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     * @param id
     * @return void
     * @description: 回收站中删除商品, 真正的物理删除, 将数据从数据库中删除掉
     * @author 大佬味的小男孩
     * @date 2020/07/20 18:40
     */
    @Override
    @Transactional
    public void deleteTrue(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //判断商品是否存在
        if (spu == null) {
            MyBaseException.throwe(ResultCode.DATA_NOT_EXIST);
        }
        //检查是否删除的商品
        if ("1".equals(spu.getIsDelete())) {
            MyBaseException.throwe(ResultCode.ITEM_NOT_DELETED);
        }
        spuMapper.deleteByPrimaryKey(id);
    }

    /**
     * @param id
     * @return com.changgou.goods.pojo.Spu
     * @description: 根据spu id 查询spu数据
     * @author 大佬味的小男孩
     * @date 2020/07/27 21:48
     */
    @Override
    public Spu findById(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        return spu;
    }


    /**
     * @param goods
     * @return void
     * @description: 添加商品的sku
     * @author 大佬味的小男孩
     * @date 2020/07/19 16:44
     */
    private void saveSkuList(Goods goods) {
        //获得sku
        List<Sku> skuList = goods.getSkuList();
        for (Sku sku : skuList) {
            //添加分布式id
            sku.setId(String.valueOf(idWorker.nextId()));
            //设置sku的规格
            if (sku.getSpec() == null && "".equals(sku.getSpec())) {
                sku.setSpec("{}");
            }
            //sku的名称(sku + 规格数据)
            String name = sku.getName();
            String spec = sku.getSpec();
            //将规格参数json转化成map
            Map<String, String> specmap = JSON.parseObject(spec, Map.class);
            //遍历map
            if (specmap != null && specmap.size() > 0) {
                for (String value : specmap.values()) {
                    name += value;
                }
            }
            //设置suk名称
            sku.setName(name);
            //设置sku的创建时间
            sku.setCreateTime(new Date());
            //设置sku的修改时间
            sku.setUpdateTime(new Date());

            //获取spu对象
            Spu spu = goods.getSpu();
            //获取品牌对象
            Brand brand = brandMapper.selectByPrimaryKey(spu.getBrandId());
            //获取分类对象
            Category category = categoryMapper.selectByPrimaryKey(spu.getCategory3Id());

            /*
             *分类和品牌表中：添加spu中的分类ip与品牌ip之间的关联
             */
            CategoryBrand categoryBrand = new CategoryBrand();
            //拿到spu中的品牌id
            categoryBrand.setBrand_id(spu.getBrandId());
            //拿到spu中的第三级分类
            categoryBrand.setCategory_id(spu.getCategory3Id());
            int count = categoryBrandMapper.selectCount(categoryBrand);
            //判断是否有这个品牌和分类的关系数据
            if (count == 0) {
                //如果没有关系数据则添加品牌和分类关系数据
                categoryBrandMapper.insert(categoryBrand);
            }

            //获得spuid
            String spuid = spu.getId();
            //设置sku中的spuid
            sku.setSpuId(spuid);
            //设置sku的商品分类id
            sku.setCategoryId(category.getId());
            //设置sku的商品分类名称
            sku.setBrandName(category.getName());
            //设置sku的品牌名称
            sku.setBrandName(brand.getName());
            //插入数据
            System.out.println("sku数据：" + sku);
            skuMapper.insertSelective(sku);
        }

    }
}
